package com.imay.videorecord.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.imay.videorecord.R;
import com.imay.videorecord.adapter.FilterImageAdapter;
import com.imay.videorecord.filter.base.MagicCameraInputFilter;
import com.imay.videorecord.filter.base.gpuimage.GPUImage;
import com.imay.videorecord.filter.helper.MagicFilterType;
import com.imay.videorecord.utils.ImayCons;
import com.imay.videorecord.utils.ImayParams;
import com.imay.videorecord.utils.ImayUtils;
import com.imay.videorecord.utils.MagicFilterTools;
import com.imay.videorecord.view.AutoAdjustRecylerView;
import com.imay.videorecord.view.player.FilteredVideoCallBack;
import com.imay.videorecord.view.player.FilteredVideoView;

import java.util.ArrayList;



/**
 * Created by ZhouZeChao on 2017/1/3.
 */
public class VideoClipActivity  extends Activity implements View.OnClickListener {

    private final String TAG = VideoClipActivity.class.getSimpleName();

    private Context mContext;
    private Dialog mDialog;

    private ImageView mIvClose;
    private ImageView mIvClip;

    // 滤镜
    private AutoAdjustRecylerView mRecyclerView;
    private FilterImageAdapter mAdapter;
    private MagicFilterTools mFilterTools;

    // 视频播放控件
    private FilteredVideoView  mVideoClipPlayer;
    private ImageView mIvVideoPlayer;

    // 视频路径
    private String uri;

    /**
     * 跳转
     */
    private final int REQUEST_CLIP_VIDEO = 2;

    /**
     * ==============滤镜数据=============
     */
    private GPUImage mGPUImage;

    private boolean mIsFinish = true;

    /**
     * 是否需要改变滤镜
     */
    private boolean mIsChangeFilter = false;
    private int mPositionFilter = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video_clip);

        mContext = this;

        initData();
        initView();
        initListener();
    }

    // 初始化数据信息
    private void initData() {
        // 弹出loading框
        if(mDialog == null){
            final String string = getString(R.string.ic_mov_msg_filter_loading);
            mDialog = ImayUtils.createDialog(mContext, string==null?"":string);
        }
        //mDialog.show();

        // 视频路径
        uri = getIntent().getStringExtra(ImayParams.fileUri);
        // 滤镜init
        mFilterTools = MagicFilterTools.getInstance(mContext);

        mGPUImage = new GPUImage(mContext);
        Bitmap mBitmap = ImayUtils.getVideoThumbnail(mContext,uri);
        if(mBitmap != null){
            Bitmap thumbBitmap = ThumbnailUtils.extractThumbnail(mBitmap, 75, 75);    //得到缩略图
            initBitmapList(thumbBitmap);   //初始化滤镜列表
        }else{
            //mDialog.dismiss();
        }
        ImayUtils.recycledBitmap(mBitmap);
    }

    // 初始化控件信息
    private void initView() {
        // 关闭
        mIvClose = (ImageView) findViewById(R.id.iv_close);

        // 截取
        mIvClip = (ImageView)findViewById(R.id.iv_clip);

        // 滤镜
        mRecyclerView = (AutoAdjustRecylerView) findViewById(R.id.arv_video_clip_fitter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayout.HORIZONTAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setPxPerMillsec(1.0f);
        mAdapter = new FilterImageAdapter(this);
        mAdapter.setNames(mFilterTools.getFilterNames(mContext));
        mRecyclerView.setAdapter(mAdapter);

        // 播放视频
        mVideoClipPlayer = (FilteredVideoView) findViewById(R.id.mv_video_clip_player);
        RelativeLayout.LayoutParams lp1 = (RelativeLayout.LayoutParams) mVideoClipPlayer.getLayoutParams();
        lp1.width = ImayCons.screenW;
        lp1.height = ImayCons.screenW;
        mVideoClipPlayer.setLayoutParams(lp1);
        if(!TextUtils.isEmpty(uri)){
            mVideoClipPlayer.setVideoPath(uri);
        }
        mVideoClipPlayer.setVisibility(View.VISIBLE);

        // 播放按钮
        mIvVideoPlayer = (ImageView) findViewById(R.id.iv_video_player);

        // 获取视频第一帧的图片显示在布局上
        mVideoClipPlayer.playVideo();
        new Thread(){
            @Override
            public void run() {
                super.run();
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mHandler.sendEmptyMessage(1);
            }
        }.start();
    }

    // 初始化监听信息
    private void initListener() {
        mIvClose.setOnClickListener(this);

        mIvClip.setOnClickListener(this);

        mVideoClipPlayer.setOnClickListener(this);
        mAdapter.setItemOnClickListener(new FilterImageAdapter.AutoAdjustItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                updateFilter(position);
            }
        });

        mIvVideoPlayer.setOnClickListener(this);

        mVideoClipPlayer.setBack(new FilteredVideoCallBack() {
            @Override
            public void preparePlay(int width, int height) {
                //设置surfaceView的布局参数
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mVideoClipPlayer.getLayoutParams();
                lp.width = width;
                lp.height = height;
                mVideoClipPlayer.setLayoutParams(lp);
            }

            @Override
            public void playbackFinish() {
                mIvVideoPlayer.setVisibility(View.VISIBLE);
                mVideoClipPlayer.stopVideo();
                mVideoClipPlayer.setClickable(false);
            }
        });
    }

    /**
     * 改变滤镜
     * @param position
     */
    private void updateFilter(int position) {
        if(position != 0){
            mPositionFilter = position;
            mIsChangeFilter = true;
        }else{
            mPositionFilter = 0;
            mIsChangeFilter = false;
        }
        /**
         *
         */
        MagicFilterType type = MagicFilterTools.getInstance(mContext).getFilterType(position);
        if(type == MagicFilterType.ORIGINAL){
            mVideoClipPlayer.setFilter(new MagicCameraInputFilter(mContext));
        }else{
            mVideoClipPlayer.setFilter(MagicFilterTools.getInstance(mContext).createFilterForType(mContext,type));
        }
        mAdapter.setSelectedPostion(position);
        mRecyclerView.checkAutoAdjust(position);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        int r = view.getId();
        if(r == R.id.iv_close){
            finish();
        }else if(r == R.id.mv_video_clip_player){
            mIvVideoPlayer.setVisibility(View.VISIBLE);
            mVideoClipPlayer.stopVideo();
            mVideoClipPlayer.setClickable(false);
        }else if(r == R.id.iv_video_player){
//            mIvVideoClip.setVisibility(View.INVISIBLE);
            mIvVideoPlayer.setVisibility(View.INVISIBLE);
            mVideoClipPlayer.setClickable(true);
            mVideoClipPlayer.playVideo();
        }else if(r == R.id.iv_clip){
            /**
             * 改变滤镜必须通过surface重新写入数据并导出mov
             */
//            Intent intent = new Intent(VideoClipActivity.this, LoadingDialogActivity.class);
//            intent.putExtra(ImayParams.fileUri, uri);
//            intent.putExtra(ImayParams.fileClipFilter,mPositionFilter);
//            intent.putExtra(ImayParams.fileClipIsChangeFilter,mIsChangeFilter);
//            startActivityForResult(intent,REQUEST_CLIP_VIDEO);
//            // 跳转动画
//            overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
            //overridePendingTransition(R.anim.zoomin,R.anim.zoomout);

        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        // 删除视频文件
        ImayUtils.deleteMovFile(this,uri);
    }

    // 滤镜缩略图
    private void initBitmapList(final Bitmap thumbBitmap) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (mFilterTools.getFilterNames(mContext) == null)
                    mFilterTools = MagicFilterTools.getInstance(mContext);
                ArrayList<Bitmap> mBitmapList = new ArrayList<>();
                final int size = mFilterTools.getFilterNames(mContext).size();
                for (int i = 0; i < size; i++) {
                    if (thumbBitmap == null)
                        break;
                    try {
                        //滤镜设置缩略图
                        mGPUImage.setImage(thumbBitmap);
                        if(i == 0){
                            mGPUImage.setFilter(new MagicCameraInputFilter(mContext));
                        }else{
                            mGPUImage.setFilter(mFilterTools.getGPUImageFilter(mContext, i));
                        }
                        //Thread.sleep(100);//等待100毫秒，让GPUImage完成渲染，再取值
                        //GPUImage线程不安全
                        //mGPUImage.getBitmapWithFilterApplied()取的数据可能为空数据，
                        mBitmapList.add(mGPUImage.getBitmapWithFilterApplied());
                        //mHandler.sendEmptyMessage(0);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                ImayUtils.recycledBitmap(thumbBitmap);
                mAdapter.setBitmapList(mBitmapList);
                Message msg = new Message();
                //msg.obj = mDialog;
                msg.what = 0;
                mHandler.sendMessage(msg);
            }
        }).start();
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mAdapter.notifyDataSetChanged();
                    mDialog.dismiss();
                    break;
                case 1:
                    mVideoClipPlayer.stopVideo();
                    break;
                case 2:
                    String imgpath = (String) msg.obj;
                    Bundle bundle = new Bundle();
                    bundle.putString(ImayParams.movUri,uri);
                    bundle.putString(ImayParams.imgUri,imgpath);
                    getIntent().putExtras(bundle);
                    setResult(RESULT_OK, getIntent());
                    finish();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mVideoClipPlayer.release();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_CLIP_VIDEO){
            if (resultCode == RESULT_OK) {
                Bundle bundle = new Bundle();
                bundle.putString(ImayParams.movUri,data.getStringExtra(ImayParams.movUri));
                bundle.putString(ImayParams.imgUri,data.getStringExtra(ImayParams.imgUri));
                getIntent().putExtras(bundle);
                setResult(RESULT_OK, getIntent());
                finish();
            }
        }
    }
}
